<template>
    <div>
        <el-card>
            <!-- 顶部 搜索框 -->
            <el-input v-model="search.keyword" style="max-width: 30rem;margin-right: 1rem;" placeholder="请输入查询物品名称"
                clearable @clear="getGoods">
                <template #prepend>
                    <el-button :icon="Search" @click="getGoods" />
                </template>
                <template #append>
                    <el-select v-model="selectValue" placeholder="搜索建议" style="width: 7rem" @change="changeSelect">
                        <el-option label="武器" value="武器" />
                        <el-option label="药水" value="药水" />
                        <el-option label="道具" value="道具" />
                    </el-select>
                </template>
            </el-input>
            <el-button @click="openAddDialog">添加商品</el-button>
            <!-- 列表 -->
            <el-table :data="tableData" border style="width: 100%;margin-top: 1rem;"
                :default-sort="{ prop: 'price', order: 'descending' }">
                <el-table-column type="index" width="50" label="#" align="center" />
                <el-table-column prop="name" label="名称" width="180" align="center" />
                <el-table-column prop="num" label="数量" width="60" align="center" />
                <el-table-column prop="price" label="价格" width="100" align="center" sortable />
                <el-table-column prop="description" label="描述" />
                <el-table-column label="类型" width="80" align="center">
                    <template #default="scope">
                        <el-tag :type="statusMap.get(scope.row.type)">{{ scope.row.type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="图片" width="100" align="center">
                    <template #default="scope">
                        <img :src="`/api` + scope.row.img" class="rounded-md w-[4.5rem] h-[4.5rem]">
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" @click="editForm(scope.row)" />
                        <el-popconfirm title="确定删除该商品吗?" @confirm="deleteGood(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" :icon="Delete" />
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加/修改商品对话框 -->
            <el-dialog @close="addGoodsColse" v-model="addGoods" :title="dialogTitle" width="500" center>
                <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="auto" status-icon>
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="addForm.name" placeholder="请输入名称" />
                    </el-form-item>
                    <el-form-item label="价格" prop="price">
                        <el-input-number v-model="addForm.price" :precision="0" :min="1" />
                    </el-form-item>
                    <el-form-item label="数量" prop="num">
                        <el-input-number v-model="addForm.num" :precision="0" :min="0" />
                    </el-form-item>
                    <el-form-item label="描述">
                        <el-input v-model="addForm.description" :rows="3" type="textarea" placeholder="请输入描述"
                            show-word-limit maxlength="100" />
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="addForm.type" placeholder="请选择类型" style="width: 8rem">
                            <el-option label="武器" value="武器" />
                            <el-option label="药水" value="药水" />
                            <el-option label="道具" value="道具" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="图片" prop="img">
                        <el-upload :file-list="fileList" :limit="1" :on-exceed="handleExceed" action="/api/upload/album"
                            list-type="picture-card" :on-preview="handlePictureCardPreview"
                            :on-success="handleAvatarSuccess">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-dialog v-model="dialogVisible" width="20%" class="flex justify-center items-center h-60">
                            <img w-full :src="dialogImageUrl" alt="Preview Image" />
                        </el-dialog>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="addGoods = false">取消</el-button>
                        <el-button type="primary" @click="save(addFormRef)">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 分页 -->
            <el-pagination :default-page-size="5" @current-change="changeSize"
                style="display: flex; justify-content: center;align-items: center; margin-top: 1rem;" background
                layout="prev, pager, next" :total="total" />
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import type { addFormType } from "../types"
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { addGoodApi, getGoodApi, delGoodApi, updateGoodApi } from "../api"
const search = reactive({
    page: 1,
    pageSize: 5,
    keyword: ''
})
const selectValue = ref('')
const dialogImageUrl = ref('')
const dialogTitle = ref('添加商品')
const addGoods = ref(false)
const dialogVisible = ref(false)
const total = ref(0)
const addFormRef = ref<FormInstance>()
const tableData = ref([])
const fileList = ref<UploadUserFile[]>([])
const addForm = reactive<addFormType>({
    id: 0,
    name: '',
    description: '',
    price: 1,
    type: '',
    img: '',
    num: 1
})
// 类型映射
const statusMap = new Map([['武器', 'warning'], ['药水', 'success'], ['道具', 'danger']])
//清空数据
const resetForm = reactive({ ...addForm })
onMounted(() => {
    getGoods()
})
// 获取商品列表
const getGoods = async () => {
    const res = await getGoodApi(search)
    tableData.value = res.data.result
    total.value = res.data.total
}
// 商品验证
const addRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }, { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }],
    price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
    num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    img: [{ required: true, message: '请上传图片', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
})
// 添加商品弹窗
const openAddDialog = () => {
    addGoods.value = true
    Object.assign(addForm, resetForm)
}
// 预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
// 图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, file) => {
    if (response.data.code === 200) {
        addForm.img = response.data.filename
    }
    fileList.value.push(file)
}
// 图片上传数量限制
const handleExceed: UploadProps['onExceed'] = () => {
    return ElMessage.warning('超出上传数量')
}
// 确认添加商品
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            if (addForm.id) {
                let res = await updateGoodApi(addForm)
                if (res.data.code === 200) {
                    ElMessage.success('修改成功')
                }
            }
            else {
                let res = await addGoodApi(addForm)
                if (res.data.code === 200) {
                    ElMessage.success('添加成功')
                }
            }
            getGoods()
            addGoods.value = false
        } else {
            ElMessage.warning('请检查填写信息')
        }
    })

}
// 搜索下拉菜单
const changeSelect = (value: string) => {
    search.keyword = value
    getGoods()
}
// 分页
const changeSize = (page: number) => {
    search.page = page
    getGoods()
}
// 删除商品
const deleteGood = (id: number) => {
    delGoodApi(id).then(res => {
        if (res.data.code === 200) {
            ElMessage.success('删除成功')
            getGoods()
        }
    })
}
// 修改商品
const editForm = (row: addFormType) => {
    fileList.value = [{
        url: `/api/${row.img}`,
        name: ''
    }]
    dialogTitle.value = '修改商品'
    addGoods.value = true
    Object.assign(addForm, row)
}
// 商品弹窗关闭
const addGoodsColse = () => {
    fileList.value = []
    addFormRef.value?.resetFields()
}
</script>

<style scoped></style>
